import { NextRequest, NextResponse } from 'next/server'
import { loginUser } from '@/lib/auth-service'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { email, password } = body

    const result = await loginUser({ email, password })

    if (result.success) {
      const response = NextResponse.json({
        success: true,
        user: result.user,
        token: result.token, // 同时在响应体中返回token
        message: '登录成功'
      })

      // 设置HTTP-only cookie (作为备用认证方式)
      response.cookies.set('auth-token', result.token!, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 7 * 24 * 60 * 60, // 7天
        path: '/' // 确保cookie在整个域名下可用
      })

      return response
    } else {
      return NextResponse.json({
        success: false,
        error: result.error
      }, { status: 401 })
    }
  } catch (error) {
    console.error('登录API错误:', error)
    return NextResponse.json({
      success: false,
      error: '服务器内部错误'
    }, { status: 500 })
  }
}